<?php
/**
 * @description:
 * @author     : Geomen
 * @time       : 2018/10/19 11:37
 */


namespace App\Http\Controllers;


use App\Http\Resources\ImageCollection;
use App\Models\Image;
use App\Models\ImgLike;
use App\Models\User;
use Illuminate\Http\Request;

class ImgController extends Controller
{
    /**
     * 上传图片
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function upload(Request $request)
    {
        $img = $request->file('img');
        if ($img->isValid()){
            $path = $img->store('img');
            Image::query()->create(['url' => $path,'open_id' => $request->input('open_id')]);
            return response(['state' => 'success','path' => $path]);
        }else{
            return response(['state' => 'fail','msg' => '图片上传失败']);
        }
    }

    /**
     * 获取图片列表
     *
     * @param Request $request
     *
     * @return ImageCollection
     */
    public function get(Request $request){
        $open_id = $request->input('open_id');
        $list = Image::query()->with(['user','imgLike' => function($query) use ($open_id){
            $query->where('open_id',$open_id);
        }])->latest()->paginate(10);
        return new ImageCollection($list);
    }

    /**
     * 删除图片
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function del(Request $request)
    {
        $id = intval($request->input('id'));
        $info = Image::query()->findOrFail($id);
        $del = \Storage::delete($info->url);
        $info->delete();
        ImgLike::query()->where('img_id',$id)->delete();
        return response(['state' => 'success','msg' => '图片删除成功','result' => $del]);
    }

    /**
     * 获取点赞记录
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getLike(Request $request)
    {
        $open_id = $request->input('open_id');
        $list = ImgLike::query()->where('open_id',$open_id)->pluck('img_id');
        return $this->responseSuccess('',$list);
    }

    /**
     * 添加点赞记录
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function addLike(Request $request)
    {
        $like = ImgLike::query()->firstOrCreate($request->only(['open_id','img_id']));
        if ($like->wasRecentlyCreated){
            Image::query()->where('id',$request->input('img_id'))->increment('like_count');
        }
        return $this->responseSuccess('点赞成功');
    }
}